package com.shenjies88.practice.reactor;


import com.shenjies88.practice.reactor.hold.SelectorWrapperHold;
import com.shenjies88.practice.reactor.hold.WorkWrapperHold;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * @author shenjies88
 * @since 2022/12/7/19:24
 */
public class ServerApplication {


    public static void main(String[] args) {
        try (var serverSocketChannel = ServerSocketChannel.open();
             var selector = Selector.open()) {
            serverSocketChannel.socket().bind(new InetSocketAddress(8080));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            SelectorWrapperHold.init();
            WorkWrapperHold.init();
            System.out.println("服启动成功");
            while (true) {
                if (selector.select() == 0) {
                    continue;
                }
                var selectionKeys = selector.selectedKeys();
                var iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    var selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        var socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        SelectorWrapperHold.register(socketChannel);
                        iterator.remove();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("服务器运行异常");
            System.exit(1);
        }
    }
}
